#!/bin/bash

set -x
#
# Define constrains
#
RETRY_MAX=3
RETRY_INTERVAL=1800 # half hour
NOTIFY_TO="wox_notify_grp@oracle.com"


#
# Define function
#
function usage () {
    cat <<EO_USAGE
usage: $basenm [-f] build_type
       $basenm [-f] os_release build_type build_no

  -f            force to run this script even if the build
                is already handled by this script. 

  build_type    os, dt

  os_release    s11u1/2/3/..., s12

EO_USAGE
    exit 1
}

# notify build not available
# arg1: os release
# arg2: build type, os, dt
# arg3: build no.
# arg4: repo
# arg5: check cmd
function notify_build_na () {
    mailx -s "[WOX PROCM]: $1 $2 build $3 not available in repo." $NOTIFY_TO << EO_MAIL

OS Release: $1
Build Type: $2
Build NO. : $3 
IPS Repo. : $4
Check Cmd : $5

EO_MAIL
}

# arg1: os release
# arg2: build type, os, dt
# arg3: build no.
function check_build () {
    typeset bno=${3//[^0-9]/}
    typeset bno_s=""
    if [ $bno -lt 10 ]; then
        # strip leading '0's
        bno_s="`echo $bno |sed 's/^0*//'`"
        # with leading '0'
        bno="0${bno_s}"
    else
        bno_s=$bno
    fi

    typeset repo=""
    typeset ips_bno=""
    typeset chk_pkg=""
    case "$2" in
      os)
        repo="http://pkg801.cn.oracle.com/$1/"
        chk_pkg="release/name"
        ;;
      dt)
        repo="file:///net/ipsbj.cn.oracle.com/dtrepo/$1/$bno/"
        chk_pkg="consolidation/desktop/*"
        ;;
      *)
        usage
        ;;
    esac

    case "$1" in
      s12)
        ips_bno="5.12.0.0.0.$bno_s"
        ;;
      s11u*)
        ips_bno="0.175.${1#s11u}.0.0.$bno_s"
        ;;
      *)
        usage
        ;;
    esac

    typeset chk_cmd="pkg info -r -g $repo $chk_pkg@*-$ips_bno"
    typeset retry=0
    while /bin/true; do
        if ($chk_cmd >/dev/null 2>&1); then
            # build is there, let's move on
            break
        else
            # build is N/A
            if [ "$2" == "dt" -a $retry -lt $RETRY_MAX ]; then
                # retry it
                retry=`expr $retry + 1`
                sleep $RETRY_INTERVAL
            else
                # send notification and exit
                notify_build_na $1 $2 $3 $repo "$chk_cmd"
                exit 2
            fi
        fi
    done
}


#
# Main
#
basenm="`basename $0`"
log="/tmp/${basenm}.log"

# redirect stdout/stderr to log file
exec >> $log 2>&1

print "start at `date`"

opt_f=""
while getopts f opt; do
    case "$opt" in
      f)
        opt_f="yes"
        ;;
      \?|h)
        usage
        ;;
    esac
done
shift `expr ${OPTIND} - 1`

mydir="`cd $(dirname $0); pwd`"
build_history="/var/tmp/${basenm}.his"

build_type=""
# placehoder, it's not used yet
site=""
os_rel=""
build_no=""
repo=""

if [ $# -eq 1 ]; then
    # get other arguments from subject
    build_type=$1

    # parse the subject of build annouce emails
    # note: just need to pass 1 argument to grep 
    # here, because the input is from the pipe
    sub="`grep '^Subject:' | tr '[:upper:]' '[:lower:]'`"
    case "$build_type" in
      os)
        # subject e.g.: "Subject: [OS BUILD]:zpk:s12:13:"
        # strip space char
        sub=${sub// /}
        typeset -a sf=(${sub//:/ })
        site=${sf[2]}
        os_rel=${sf[3]}
        build_no=${sf[4]}
        ;;
      dts12)
        build_type="dt"
        # subject e.g.: "Subject: FWD: s12_23 desktop packages ready for testing."
        typeset -a sf=(${sub##*:})
        os_rel=${sf[0]%_*}
        build_no=${sf[0]#*_}
        ;;
      dts11ux)
        build_type="dt"
        # subject e.g.: "Subject: FWD: JDS S11U2 build 16 are ready for testing"
        typeset -a sf=(`echo ${sub} | sed -e 's/^.*[ 	]s11/s11/'`)
        os_rel=${sf[0]}
        build_no=${sf[2]}
        ;;
      *)
        usage
        ;;
    esac
elif [ $# -eq 3 ]; then
    # get all arguments from cmd line
    os_rel=$1
    build_type=$2
    build_no=$3
else
    usage
fi

# validate build no.
typeset build_no_digit=${build_no//[^0-9]/}
if [ -z "${build_no_digit}" ]; then
    print -u2 "ERROR: invalid build no. $build_no"
    exit 1
fi
# add leading '0' for build 1 - 9
test ${build_no_digit} -lt 10 && build_no="0${build_no}"


# check if the build is already handled or not
is_handled=""
his="$os_rel:$build_type:$build_no:"
print "look up build history"
grep "^$his" $build_history >/dev/null 2>&1
if [ $? -eq 0 ]; then
    is_handled="yes"
    if [ -z "$opt_f" ]; then
        print -u2 "ERROR: the build already been handled, abort"
        exit 3
    fi
fi
    
# check if the build is there
print "check if the build is there"
check_build $os_rel $build_type $build_no

# update OS build list
if [ "$build_type" == "os" ]; then
    print "update OS build list"
    $mydir/genbldlst.py
fi

print "trigger wox inst"
$mydir/bgtrigger.py ai $os_rel $build_type $build_no

if [ $? -eq 0 ]; then
    # record this build in history file
    if [ -z "$is_handled" ]; then
        if [ -s $build_history ]; then
            printf "1i\n%s\n.\nw" "$his" | ed -s $build_history
        else
            print "$his" > $build_history
        fi
    fi
else
    # send notification if trigger failed
    mailx \
      -s "[WOX PROCM]: $os_rel $build_type build $build_no - trigger wox failed" \
      $NOTIFY_TO <<EO_MAIL

`tail $log`

EO_MAIL
fi

print "end at `date`\n"
